package com.hwadee.JPKC.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.hwadee.JPKC.entity.courseView;
import com.hwadee.JPKC.service.CourseInfoService;
import com.hwadee.JPKC.service.courseViewService;

@Controller
@RequestMapping("/upload")
public class DownloadController {

	@Autowired
	private ServletContext application;
	@Autowired
	private courseViewService courseviewservice;
	
	@PostMapping
	// 上传文件
	public String postFile(MultipartFile file) throws IOException {

		// 得到文件名
		String path = application.getRealPath("/upload");

		// 文件存储路径
		String ofn = file.getOriginalFilename();
		System.out.println(ofn);
		System.out.println(path);

		FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path, UUID.randomUUID().toString() + ofn));
		return "redirect:/test/hui";
	}

	@RequestMapping("/download")
	//下载文件
	public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {

		String path = request.getServletContext().getRealPath("/upload/");//得到下载文件夹的路径
		String fileName = request.getParameter("filename");//得到下载文件名
		File file = new File(path + fileName);
		if (file.exists()) {
			// 设置MIME类型
			response.setContentType("application/octet-stream");
			// 或者为response.setContentType("application/x-msdownload");

			// 设置头信息,设置文件下载时的默认文件名，同时解决中文名乱码问题
			response.addHeader("Content-disposition",
					"attachment;filename=" + new String(fileName.getBytes(), "ISO-8859-1"));

			InputStream inputStream = new FileInputStream(file);
			ServletOutputStream outputStream = response.getOutputStream();
			byte[] bs = new byte[1024];
			while ((inputStream.read(bs) > 0)) {
				outputStream.write(bs);
			}
			outputStream.close();
			inputStream.close();
		}
	}
	
	//Ajax上传文件
		@RequestMapping(value = "/upload2", method = RequestMethod.POST)
		//@ResponseBody
		public @ResponseBody String upload(int courseId,String cName,String courseView,@RequestParam("file") MultipartFile file,
				HttpServletRequest request) {
			
			Map<String, String> modelMap = new HashMap<>();
			if (!file.isEmpty()) {
				String storePath = application.getRealPath("/upload");
				String fileName = file.getOriginalFilename();
				String[] split = fileName.split("\\.");
				fileName = split[0] + UUID.randomUUID().toString()+"."+split[1];
				//fileName = fileName + ".png";//文件名
				courseView courseView1= new courseView();
				courseView1.setCourseId(courseId);
				courseView1.setCourseDescription(cName);
				courseView1.setCourseView(courseView);
				courseView1.setViewRul(fileName);
				courseviewservice.insert(courseView1);
				File filePath = new File(storePath, fileName);
				if (!filePath.getParentFile().exists()) {
					filePath.getParentFile().mkdirs();// 如果目录不存在，则创建目录
				}
				try {
					file.transferTo(new File(storePath + File.separator + fileName));// 把文件写入目标文件地址
				} catch (Exception e) {
					e.printStackTrace();
					modelMap.put("back", "error");
					String json = JSON.toJSONString(modelMap);
					return json;
				}
				modelMap.put("back", "success");
	 
			} else {
				modelMap.put("back", "error");
			}
			String json = JSON.toJSONString(modelMap);
			return json;
	 
		}

		
		@RequestMapping(value = "/upload3", method = RequestMethod.POST)
		//@ResponseBody
		public @ResponseBody String upload3(int courseId,String cName,String courseWen,@RequestParam("file") MultipartFile file,
				HttpServletRequest request) {
			Map<String, String> modelMap = new HashMap<>();
			if (!file.isEmpty()) {
				String storePath = application.getRealPath("/upload");
				String fileName = file.getOriginalFilename();
				String[] split = fileName.split("\\.");
				fileName = split[0] + UUID.randomUUID().toString()+"."+split[1];
				//fileName = fileName + ".png";//文件名
				courseView courseView= new courseView();
				courseView.setCourseId(courseId);
				courseView.setCourseDescription(cName);
				courseView.setCourseWen(courseWen);
				courseView.setWenRul(fileName);
				courseviewservice.insert(courseView);
				File filePath = new File(storePath, fileName);
				if (!filePath.getParentFile().exists()) {
					filePath.getParentFile().mkdirs();// 如果目录不存在，则创建目录
				}
				try {
					file.transferTo(new File(storePath + File.separator + fileName));// 把文件写入目标文件地址
				} catch (Exception e) {
					e.printStackTrace();
					modelMap.put("back", "error");
					String json = JSON.toJSONString(modelMap);
					return json;
				}
				modelMap.put("back", "success");
	 
			} else {
				modelMap.put("back", "error");
			}
			String json = JSON.toJSONString(modelMap);
			return json;
	 
		}

}
